import { Component, OnInit } from '@angular/core';
import { BladeContainerInterface } from "../../../../shared/blade/blade-container.interface";
import { Blade } from "../../../../shared/blade/blade.model";
import { Observable } from "rxjs/Observable";
import { FormBuilder, FormGroup, Validators, FormControl } from "@angular/forms";
import { SimpleChanges } from "@angular/core/core";
import { Command } from "../../../../shared/toolbar.service";
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { BladeData } from "../../../../shared/blade/blade-data";
import { MyValidators } from "../../../../utils/validator/rang";

//自定义状态表达式数据模型
import { MatrixStateExpr } from "../../../../entity/matrix-state-expr.model"

import { MatrixLogic } from "../../../../entity/matrix_logic.model";
import { MatrixLogicService } from "../../../../service/matrix-logic.service";

@Component({
	selector: 'app-matrix-logic-edit',
	templateUrl: './matrix-logic-edit.component.html',
	styleUrls: ['./matrix-logic-edit.component.css']
})
export class MatrixLogicEditComponent extends BladeContainerBase<MatrixStateExpr> {

	canSave: boolean;
	public inputValue: number = 1;

	/**
   * 验证结果
   * 
   * @type {boolean}
   * @memberof MatrixLogicEditComponent
   */
	result: boolean;

	constructor(
		private fb: FormBuilder,
		private matrixLogicService: MatrixLogicService,
	) { super(fb) }

	ngOnInit() {
		//编辑时注册按钮和按钮命令    	
		this.commands = [
			new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
			new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
		]
		super.ngOnInit();
	}

	/**
	 * 初始化数据
	 * 
	 * 
	 * @memberof TurbstatusValueListComponent
	 */
	initData(): any | Observable<any> | Promise<any> {
		this.formPatchValue(this.currentEntity);
	}

	exeSaveChange(blade: any): void {
		this.saveChange();
	}
	canSaveChange(blade: any): boolean {
		return (this.canSave === true) && (this.currentEntity.expression != this.formGroup.value["expression"]);
	}
	exeReset(blade: any): void {
		return this.formGroup.reset(this.currentEntity);
	}
	canReset(blade: any): boolean {
		return this.hasChange();
	}

	/**
    * 创建表单
    * 
    * 
    * @memberof DicKeyEditComponent
    */
	createForm() {
		this.formGroup = this.fromBuider.group({
			"stateName": [this.currentEntity.stateName],
			"expression": [this.currentEntity.expression, [
				Validators.required,
				Validators.maxLength(255),
			]],
			//"inputValue": [this.inputValue]
		});
		this.formGroup.controls["expression"].valueChanges.subscribe(form => {
			this.canSave = false;
		})
	}

	/**
	 * 设置表单错误对象
	* 
	* 
	* @memberof BladeContainerBase
	*/
	setFormError(): void {
		this.formErrors = {
			'expression': '',
		};
	}

	/**
	 * 设置表单验证信息
	 * 
	 * 
	 * @memberof BladeContainerBase
	 */
	setValidationMessages(): void {
		this.validationMessages = {
			'expression': {
				'required': '不能为空。',
				'maxlength': '表达式不能多于20个字符长度。'
			}

		};
	}

    /**
     * 保存
     * 
     * 
     * @memberof DicKeyEditComponent
     */
	saveChange(): any | Promise<any> | Observable<any> {
		if (this.canSaveChange(this.currentBlade)) {
			this.bladeData.isLoading = true;
			let formValue = this.formGroup.value;
			this.currentEntity.expression = formValue.expression;
			let matrixLogic = {
				logicId: this.currentEntity.logicId,
				expression: this.currentEntity.expression,
				stateId: this.currentEntity.stateId,
				logicGroupId: this.parentBlade.parentEntity.logicGroupId,
			}
			return this.matrixLogicService.update(matrixLogic)
				.then(res => {
					if (res) {
						(this.parentBlade.bladeContainerInstance).refresh(res);
						this.bladeService.closeBlade(this.currentBlade);
						return true;
					}
				})
				.catch(error => this.bladeData.error = error)
				.then(res => this.bladeData.isLoading = false);
		}
	}

	onLogicValid() {
		if (!this.hasError()) {
			this.bladeData.isLoading = true;
			let formValue = this.formGroup.value;
			//this.currentEntity.expression = formValue.expression;
			let str = formValue.expression;

			let value = this.inputValue;
			str = str.replace(new RegExp("@[A-Z]#", 'g'), function (a) {
				a = value.toString();
				return a;
			})
			this.matrixLogicService.expressionCheck(str)
				.then(res => {
					if (res.code == 200) {
						this.result = res.data.expr;
						this.canSave = true;
					} else if (res.code == -1) {
						this.result = res.message;
						this.canSave = false;
					}

					//(this.parentBlade.bladeContainerInstance).refresh(res);
				})
				.catch(error => this.bladeData.error = error)
				.then(res => this.bladeData.isLoading = false);
		}
	};
}



// WEBPACK FOOTER //
// ./src/app/module/basic/matrix-config/matrix-logic-edit/matrix-logic-edit.component.ts